package com.hfzy.ihk.web.websocket.support.toApp.handler;

import com.alibaba.fastjson.JSONObject;
import com.hfzy.ihk.common.util.date.DateUtils;
import com.hfzy.ihk.common.util.string.StringUtil;
import com.hfzy.ihk.web.websocket.constant.Constants;
import com.hfzy.ihk.web.websocket.support.base.WebSocketMessageHandler;
import com.hfzy.ihk.web.websocket.utils.SpringWebSocketUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/12/1.
 *
 * @author wws
 */
@Component
public class AppWebSocketMessageHandler implements WebSocketMessageHandler {

    private static final Logger logger = LoggerFactory.getLogger(AppWebSocketMessageHandler.class);

//    @Resource
//    ClickCallToAppService clickCallToAppService;
//    @Resource
//    MsgPhoneRmiService msgPhoneRmiService;

//    public void setClickCallToAppService(ClickCallToAppService clickCallToAppService) {
//        this.clickCallToAppService = clickCallToAppService;
//    }

    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) {

        Map<String, String> map  = null;
        String msgType = null;
        String sessionId = null;
        String hasRecordFile = null;
        String recordTime = null;
        String countTime = null;
        String voiceMsg = null;
        String desc = null;
        String errorCode = null;

        String stateJson = message.getPayload().toString();
        try {
            Map<String,Object> attributes = session.getAttributes();

            if(stateJson.indexOf("BEAT")==-1)
                logger.info("app msg:{},userId:{},sid:{}",stateJson,attributes.get("userId"),session.getId());

            JSONObject json = JSONObject.parseObject(stateJson);

            msgType     = json.get("msgType")  == null?null:json.get("msgType").toString();
            sessionId   = json.get("sessionId")== null?null:json.get("sessionId").toString();
            hasRecordFile = json.get("hasRecordFile")== null?null:json.get("hasRecordFile").toString();
            recordTime = json.get("recordTime")== null?null:json.get("recordTime").toString();//录音时长
            countTime = json.get("countTime")== null?null:json.get("countTime").toString();//通话时长
            voiceMsg = json.get("voiceMsg")== null?null:json.get("voiceMsg").toString();
            desc = json.get("desc")== null?null:json.get("desc").toString();

            /**RPC 调用*/
            switch (msgType){
                case "START":
                    attributes.put("isBusy",true);
                    /*先经过后台处理，在返回到置业*/
                    /**RPC调用*/
//                    clickCallToAppService.handleCallStateWithPhone(msgType,sessionId,hasRecordFile,recordTime,countTime,voiceMsg,"开始呼叫");
                    break;
                case "ERROR":

                    errorCode = json.get("errorCode")== null?null:json.get("errorCode").toString();
                    switch (errorCode){

                        case "301":
//                            desc = "内存不足，不能拨号";
                        case "302":
//                            desc = "未能识别内存卡";
                            desc = "手机内存不足，请及时清理后再进行外呼";
                            break;

                        case "308":
                            desc = "请更新最新版合富人APP再进行外呼";
                            break;
                        case "306":
//                            desc = "暂不支持该机型：";
                        case "311":
//                            desc = "您的手机不符合拨号条件";
                            desc = "该手机机型或手机系统版本暂不支持外呼";
                            break;

                        case "307":
//                            desc = "拨号结束，倒数中";//电话挂断倒计时5秒内，再次拨打
                        case "309":
//                            desc = "通话中，不能外呼";
                            desc = "手机正在通话中，请勿再次外呼";
                            break;

                        case "310":
                            desc = "您当前正在通话的电话号码与请求挂断的不一致，不能挂断";
                            break;

                        case "312":
//                            desc = "您的手机SIM卡读取状态失败";
                        case "314":
//                            desc = "您的卡不符合当前拨号条件，请审核卡后再进行云呼";
                        case "316":
//                            desc = "您的卡槽1为空，请插入验证过的手机卡";
                              desc = "请把公司的手机卡插入卡槽1再进行外呼";
                            break;

//                        case "313":
//                            desc = "拨号准备就绪";
//                            break;

                        case "315":
//                            desc = "飞行模式，不能云呼";
                            desc = "手机开启飞行模式，请关闭后再进行外呼";
                            break;

                        case "300":
//                            desc = "拨号失败，拨号权限未开启";
                        case "317":
//                            desc = "您的权限被修改了，请正确设置好权限";
                            desc = "请打开手机的设置--应用管理--合富人，把合富人APP全部权限开启再进行外呼";
                            break;

                        case "319":
                            desc="安装了黑名单APP，请按手机提示卸载后再进行外呼";
                            break;
                        case "320":
                            desc="请确认是否录入客源再进行外呼";
                            break;
                        //case "303":
//                            desc = "您的手机不符合发送短信条件";
//                            break;
//                        case "304":
//                            desc = "您的手机SIM卡，不能进行发送短信";
//                            break;
//                        case "305":
//                            desc = "您的卡不符合当前发短信条件，请审核卡后再进行发送";
//                            break;
//                        case "318":
//                            desc = "短信发送成功";
//                            break;
                        case "321":
                            desc="请勿在多任务功能下外呼，请在手机端关闭多任务窗口。";
                            break;
                        default:
                            desc="拨号失败！";
                    }
                    desc= StringUtil.strConnect(desc,"[",errorCode,"]");
                    attributes.remove("currentCallBrowserSocketInfo");
                case "VOICE_MSG":

                    attributes.put("isBusy",false);
                    /*先经过后台处理，在返回到置业*/
                    /**RPC调用*/
//                    clickCallToAppService.handleCallStateWithPhone(msgType,sessionId,hasRecordFile,recordTime,countTime,voiceMsg,desc);

                    break;
                case "STOP":
                    attributes.put("isBusy",false);
                    attributes.remove("currentCallBrowserSocketInfo");

//                    clickCallToAppService.handleCallStateWithPhone(msgType,sessionId,hasRecordFile,recordTime,countTime,voiceMsg,"结束通话");
                    break;
                case "BEAT":

                    logger.debug("app webSocket heat beat,userId:{},sid:{}",attributes.get("userId"),session.getId());
                    map = new HashMap<>();
                    map.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE, "BEAT");
                    map.put("SID", session.getId());
                    SpringWebSocketUtils.pushToClient(session, JSONObject.toJSONString(map));
                    break;
                case "SMS":

                    String token   = json.get("token")== null?null:json.get("token").toString();
                    String phone   = json.get("phone")== null?null:json.get("phone").toString();

//                    Map<String,String> msgJsonMap = new HashMap<>();
//                    msgJsonMap.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE,AppMsgType.SEND_SMS_RES);
//                    msgJsonMap.put(Constants.WEB_SOCKET_JSON_KEY_DESC,desc);
//                    msgJsonMap.put(Constants.WEB_SOCKET_JSON_KEY_TOKEN,token);//短信发送状态靠此传回置业页面
//                    msgJsonMap.put(Constants.WEB_SOCKET_JSON_KEY_SESSION_ID,sessionId);

                    logger.debug("msg,app send success!token:{},sessionId:{},phone:{}",token,sessionId,phone);

//                    WebSocketSession browserSession = WebSocketManager.browserTokenWebSocketSessionMap.get(token);
//                    SpringWebSocketUtils.pushToClient(browserSession, JSONObject.fromObject(msgJsonMap).toString());

                    /*if(!StringUtil.isEmpty(phone)) {
                        try {
                            msgPhoneRmiService.incrMsgCountByPhone(phone);
                        } catch (Exception e) {
                            logger.error("增加短信发送统计异常");
                        }
                    }*/

                    break;
                default:

                    map = new HashMap<>();
                    map.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE, Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION);
                    map.put(Constants.WEB_SOCKET_JSON_KEY_DESC, "app消息类型异常");
                    map.put(Constants.WEB_SOCKET_JSON_KEY_SESSION_ID, sessionId);
                    map.put(Constants.WEB_SOCKET_JSON_KEY_TIME, DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME_SSS));

                    SpringWebSocketUtils.pushToClient(session, JSONObject.toJSONString(map));
                    logger.error("app webSocket handle message exception! msgType异常:{}",msgType);

                    break;
            }

        } catch (Exception e) {

            map = new HashMap<>();
            map.put(Constants.WEB_SOCKET_JSON_KEY_MSG_TYPE, Constants.WEB_SOCKET_MSG_TYPE_EXCEPTION);
            map.put(Constants.WEB_SOCKET_JSON_KEY_DESC, Constants.LOCAL_EXCEPTION_DEAL_APP_STATE);
            map.put(Constants.WEB_SOCKET_JSON_KEY_SESSION_ID, sessionId);
            map.put(Constants.WEB_SOCKET_JSON_KEY_TIME, DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT_DATETIME_SSS));

            SpringWebSocketUtils.pushToClient(session, JSONObject.toJSONString(map));

            logger.error("app webSocket处理消息异常:e:{}",e.getMessage());
        }
    }
}
